package org.amos.filestorage.platform.s3;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.amos.filestorage.exception.FileStorageException;
import org.amos.filestorage.platform.AbstractFilePlatform;
import org.amos.filestorage.platform.config.s3.AliyunFilePlatformConfig;
import org.junit.internal.Throwables;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

/**
 * 阿里云 OSS 存储
 */
public class AliyunFilePlatform extends AbstractFilePlatform<AliyunFilePlatformConfig> {

    private OSS client;

    public AliyunFilePlatform(String id, AliyunFilePlatformConfig config) {
        super(id, config);
    }

    @Override
    public void initClient() {
        client = new OSSClientBuilder().build(config.getEndPoint(), config.getAccessKey(), config.getSecretKey());
    }

    @Override
    public String upload(byte[] bytes, String path, String type) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(bytes.length);
        metadata.setContentType(type);
        client.putObject(config.getBucket(), path, new ByteArrayInputStream(bytes), metadata);
        return StrUtil.format("{}/{}", config.getDomain(), path);
    }

    @Override
    public Boolean delete(String path) {
        client.deleteObject(config.getBucket(), path);
        return Boolean.TRUE;
    }


    @Override
    public Boolean exists(String path) {
        return client.doesObjectExist(config.getBucket(), path);
    }

    @Override
    public void download(String path, Consumer<InputStream> consumer) {
        OSSObject object = client.getObject(config.getBucket(), path);
        try (InputStream in = object.getObjectContent()) {
            consumer.accept(in);
        } catch (IOException e) {
            throw new FileStorageException(Throwables.getStacktrace(e));
        }

    }
}
